package com.kuang.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @program: springboot-04-data
 * @description:
 * @author: 陈恩涛
 * @create: 2020-10-26 21:57
 **/

@Configuration
public class DruidConfig {


    /*
       将自定义的 Druid数据源添加到容器中，不再让 Spring Boot 自动创建
       绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
       @ConfigurationProperties(prefix = "spring.datasource")：作用就是将 全局配置文件中
       前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }


    //后台监控功能    web.xml<=>ServletRegistrationBean
    //因为SpringBoot内置了servlet容器，所以没有web.xml，替代方法；ServletRegisterBean
    @Bean
    public ServletRegistrationBean statViewServlet(){

        //获取druid后台监控
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        //后台需要有人登录，，账号密码配置
        HashMap<String, String> initParameters = new HashMap<>();
        //增加配置
        initParameters.put("loginUsername","admin");    //登录的key是固定的    loginUsername   loginPassword
        initParameters.put("loginPassword","123456");

        //允许谁可以访问("":代表所有人都能访问)
        //initParams.put("allow", "localhost")：表示只有本机可以访问
        //initParams.put("allow", "")：为空或者为null时，表示允许所有访问
        initParameters.put("allow","");

        //禁止谁访问
        initParameters.put("kuangshen","192.168.1.123");

        bean.setInitParameters(initParameters);//设置初始化参数

        return bean;
    }

    //filter
    @Bean
    public FilterRegistrationBean webStatFilter(){

        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(new WebStatFilter());

        //可以过滤哪些请求？
        HashMap<String, String> initParameters = new HashMap<>();

        //这些不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParameters);

        return bean;
    }

}
